// document.addEventListener('DOMContentLoaded', function() {
//   init();
// })

import { getStyles, pagePos } from '../../../utils/tools';

window.onload = function(){
  init();
}

function init(){
  initMagnifiter();
}

var initMagnifiter = (function(){
   var oLeftWrap = document.getElementsByClassName('left')[0],
       oMagWrap = oLeftWrap.getElementsByClassName('mag-pic')[0],
       oMagImg = oMagWrap.getElementsByClassName('mag-img')[0],
       magWidth = getStyles(oMagWrap, 'width'),//获取oMagWrap这个盒子的宽
       magHeight = getStyles(oMagWrap, 'height'),//获取oMagWrap这个盒子的高
       imgX = oLeftWrap.offsetLeft,//oLeftWrap这个盒子到浏览器左边的距离
       imgY = oLeftWrap.offsetTop;//oLeftWrap这个盒子到浏览器顶边的距离
    
   oLeftWrap.addEventListener('mouseover', function(e) {
      document.addEventListener('mousemove', mouseMove, false);
   }, false);

   oLeftWrap.addEventListener( 'mouseout', mouseOut, false);

   function mouseMove (e) {
      var e = e || window.event,
          x = pagePos(e).X - imgX - magWidth / 2, //pagePos(e).X 表示这个点到浏览器左边的距离
          y = pagePos(e).Y - imgY - magHeight / 2,
          mouseX = pagePos(e).X - imgX,//求出来的是，这个点，距离oLeftWrap的左右的边的距离
          mouseY = pagePos(e).Y - imgY;//求出来的是，这个点，距离oLeftWrap的上下的边的距离
          
    if (mouseX >= 80 && mouseX <= 470 && mouseY >= 45 && mouseY <= 515) {
          oMagWrap.className = 'mag-pic show';
          oMagWrap.style.left = x + 'px';
          oMagWrap.style.top = y + 'px';
          oMagImg.style.left = -x + 'px';
          oMagImg.style.top = -y + 'px';
      } else {
          oMagWrap.className = 'mag-pic';
      }

    }

    function mouseOut (e) {
       oMagWrap.className = 'mag-pic';
       document.removeEventListener('mousemove', mouseMove, false);//mousemove和mouseup事件，到最后都需要解绑掉
    }

});//这个立即执行函数里面是没有返回值的，所以最后不用加那个()，有返回值才需要加()